package com.tsugun.mediaplayer.presenter.manager

import android.app.Fragment
import android.app.FragmentManager
import android.app.FragmentTransaction
import android.content.Context
import android.view.View

import com.tsugun.mediaplayer.view.activity.BaseActivity

import java.util.ArrayList

/**
 * 页面管理
 * Created by shize on 2017/4/20.
 */

class MusicFragmentManager(context: Context) {

    private val mManager: FragmentManager
    private val mFragments: MutableList<Fragment>
    private var mContainerViewId: Int = 0
    // 共享元素标签
    private var mTransitionName: String? = null
    // 共享元素控件
    private var mView: View? = null

    private val baseActivity: BaseActivity

    init {
        mFragments = ArrayList<Fragment>()
        baseActivity = context as BaseActivity
        mManager = baseActivity.fragmentManager
    }

    /**
     * 启动fragment
     */
    fun openFragment(fragment: Fragment) {
        val transaction = mManager.beginTransaction()
        hideFragment(transaction)
        setSharedElement(transaction)
        transaction.replace(mContainerViewId, fragment)
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        transaction.addToBackStack(null)
        transaction.show(fragment)
        mFragments.add(fragment)
        transaction.commit()
        // 打开确定有 fragment
        baseActivity.hasFragment()
    }

    /**
     * 设置容器id

     * @param containerViewId 容器id
     */
    fun setContainerViewId(containerViewId: Int) {
        mContainerViewId = containerViewId
    }

    /**
     * 返回上一个fragment
     */
    fun backFragment() {
        mManager.popBackStack()
        mFragments.removeAt(mFragments.size - 1)
        if (mFragments.size < 1) {
            baseActivity.noFragment()
        }
    }

    /**
     * @return fragment数量
     */
    val count: Int
        get() = mFragments.size

    /**
     * 元素共享过渡动画

     * @param transaction 事务
     */
    private fun setSharedElement(transaction: FragmentTransaction) {
        if (mTransitionName != null && mView != null) {
            transaction.addSharedElement(mView, mTransitionName)
        }
        mTransitionName = null
        mView = null
    }

    /**
     * 隐藏fragment
     */
    private fun hideFragment(transaction: FragmentTransaction) {
        for (i in mFragments.indices) {
            transaction.hide(mFragments[i])
        }
    }
}
